import { createRouter, createWebHistory } from "vue-router";
// 引入NProgress
import NProgress from "nprogress";
// 引入nprogress样式文件
import "nprogress/nprogress.css";
import axios from "axios";
import { useUserStore } from "@/stores/user.js";
let hasGetUserInfo = false;
//createWebHistory   不带#
//createWebHashHistory 带有#
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL), //提供一个环境变量，，用来区分开发环境和生产环境
  routes: [
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/login/loginPage.vue"),
    },
    {
      path: "/",
      name: "layout",
      component: () => import("@/views/layout/layoutContainer.vue"),
      redirect: "/dashBoard",
      children: [
        {
          path: "/dashBoard",
          name: "dashBoard",
          title: "工作台",
          component: () => import("@/views/dashBoard.vue"),
          meta: ["工作台"],
        },
      ],
    },
    { path: "/404", name: "404", component: () => import("@/views/404.vue") },
    {
      path: "/:pathMatch(.*)",
      redirect: "/404",
    },
  ],
});
// 白名单
const whiteList = ["/login"];
// 全局前置导航守卫  鉴权
// 路由导航前，默认直接放行
//返回值
// 1.underfined  /true
// 2.false 拦回from地址
// 3.具体路径  拦截后，跳转到指定地址
//'/login',  {name: 'login'}
router.beforeEach(async (to, from) => {
  NProgress.start();
  // 是否有token
  const userStore = useUserStore();
  const token = userStore.token;
  if (!token && to.path !== "/login") return next("/login");
  // if (token && to.path == "/login") {
  //   return next(from.path);
  // }
  if (token && !hasGetUserInfo) {
    const res = await axios.get(
      "https://mock.mengxuegu.com/mock/639d71742e0f396e51a5c945/example/menus"
    );
    console.log(res);
    const ret = res.data.data.list;
    createRouters(ret);
    hasGetUserInfo = true;
    return to.path;
  }
  // next();
  // 关闭进度条
  NProgress.done();
});
// 拼接路由
function createRouters(result) {
  result.forEach((item) => {
    // 1、类型为0的菜单，子路由不为空，将子路由添加到manage里
    if (item.menuType === "0" && item.children.length > 0) {
      item.children.forEach((children) => {
        createRouterTemplate("Manage", children);
      });
    }
    // 2、menuType == 1, 子路由为空
    if (item.menuType === "1" && item.children.length === 0) {
      createRouterTemplate("Manage", item);
    }
    // 3、递归层级
    if (item.children.length > 0) {
      createRouters(item.children);
    }
  });
}
// 把router 的动态路由进行封装
function createRouterTemplate(fatherRouter, item) {
  router.addRoute(fatherRouter, {
    path: item.path,
    name: item.name,
    meta: {
      title: item.meta.title, // 面包屑用
      requiresAuth: item.meta.requiresAuth,
      roles: item.meta.roles,
      breadcrumb: item.meta.breadcrumb,
      keepAlive: item.meta.keepAlive,
    },
    // /* @vite-ignore */ ：处理vite动态导入的警告
    component: () => import(/* @vite-ignore */ `@/views${item.component}`),
  });
}
// // 后置守卫
router.afterEach((to, from) => {
  // 关闭进度条
  NProgress.done();
});
export default router;
